package com.jf.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketPool {
    private int count = 100;
    private Lock lock = new ReentrantLock();
    public int getTicket(){
        lock.lock();
        try{
            if(count > 0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                count--;
                return count;
            }
            System.out.println(Thread.currentThread().getName()+"已售空");
            return 0;
        }finally {
            lock.unlock();
        }
    }


//    public int getTicket(){
//        /*同步代码快方式*/
//        synchronized (this){
//            if(count > 0){
//                try {
//                    Thread.sleep(10);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                count--;
//                return count;
//            }
//            System.out.println(Thread.currentThread().getName()+"已售空");
//            return 0;
//        }
//    }

    /*同步方法*/
//    public synchronized int getTicket(){
//        if(count >0){
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            count--;
//            return count;
//        }
//        return 0;
//    }


}
